package logic

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/shopspring/decimal"
	"goods/crud"
	"goods/es"
	"time"

	"goods/goods"
	"goods/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateGoodLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateGoodLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateGoodLogic {
	return &CreateGoodLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func check(in *goods.CreateGoodRequest) error {
	if in.Info == nil {
		return fmt.Errorf("info is required")
	}

	if in.Info.Name == "" {
		return fmt.Errorf("good name is required")
	}

	if in.Info.Content == "" {
		return fmt.Errorf("good content is required")
	}

	if in.Info.Price == "" {
		return fmt.Errorf("good price is required")
	}

	_, err := decimal.NewFromString(in.Info.Price)
	if err != nil {
		return fmt.Errorf("good price is not a valid number")
	}
	return nil
}

func (l *CreateGoodLogic) createGoodToMysql(in *goods.CreateGoodRequest) (int64, error) {
	goodMod := crud.NewGoodsModel(crud.Client)
	res, err := goodMod.Insert(l.ctx, &crud.Goods{
		Name:    in.Info.Name,
		Content: in.Info.Content,
		Price:   in.Info.Price,
		Stock:   in.Info.Stock,
		CreatedAt: sql.NullTime{
			Time:  time.Now(),
			Valid: true,
		},
		UpdatedAt: sql.NullTime{
			Time:  time.Now(),
			Valid: true,
		},
	})
	if err != nil {
		return 0, err
	}

	return res.LastInsertId()
}

func (l *CreateGoodLogic) createGoodToEs(in *goods.CreateGoodRequest, id int64) error {
	return es.SaveData(fmt.Sprintf("%v", id), "good", in.Info)
}

func (l *CreateGoodLogic) CreateGood(in *goods.CreateGoodRequest) (*goods.CreateGoodResponse, error) {
	err := check(in)
	if err != nil {
		return nil, err
	}

	id, err := l.createGoodToMysql(in)
	if err != nil {
		return nil, err
	}

	err = l.createGoodToEs(in, id)
	if err != nil {
		return nil, err
	}

	return &goods.CreateGoodResponse{
		Info: &goods.Good{
			ID:      fmt.Sprintf("%v", id),
			Name:    in.Info.Name,
			Content: in.Info.Content,
			Price:   in.Info.Price,
		},
	}, nil
}
